package com.dmp.frame.core.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.Servlet;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author xufeng
 * 全局异常处理
 */
@Slf4j
@RestControllerAdvice
@Order(value = Ordered.HIGHEST_PRECEDENCE)
public class GlobalExceptionHandler {


    /**
     * 默认异常统一处理
     */
    @ExceptionHandler(Exception.class)
    public ResponseResult<?> handleException(Exception e) {
        log.error(e.toString() + "_" + e.getMessage(), e);
        return ResponseResult.systemError(GlobalCodeEnum.GL_FAIL_9999);
    }

    /**
     * 统一业务异常统一处理方法
     */
    @ExceptionHandler(ServiceException.class)
    public ResponseResult<?> handleServiceException(ServiceException e) {
        ResponseResult result = new ResponseResult<>();
        result.setCode(e.getCode());
        result.setMessage(e.getMessage());
        log.error(String.format("业务异常:%s", e.getMessage()), e);
        return result;
    }


    /**
     * 统一处理参数校验错误异常(Spring接口数据绑定验证)
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResult<?> processValidException(MethodArgumentNotValidException e) {
        List<String> errorStringList = e.getBindingResult().getAllErrors()
                .stream().map(ObjectError::getDefaultMessage).collect(Collectors.toList());
        String errorMessage = String.join("; ", errorStringList);
        log.error(String.format("参数异常:%s", e.getMessage()), e);
        return ResponseResult.systemException(GlobalCodeEnum.GL_FAIL_9998.getCode(),
                errorMessage);
    }

    /**
     * 非法参数类型异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    @ResponseStatus(value = HttpStatus.OK)
    public ResponseResult<?> handleMethodArgumentTypeMismatchExceptionHandler(MethodArgumentTypeMismatchException e) {
        log.error("参数异常:方法:{},字段:{},参数:{},错误信息:{}", e.getParameter().getMethod(), e.getName(), e.getValue(), e.getMessage());
        return ResponseResult.systemException(GlobalCodeEnum.GL_FAIL_9998.getCode(),
                "参数类型异常" + e.getName() + "," + e.getValue());
    }

    /**
     * 统一处理参数校验错误异常(非Spring接口数据绑定验证)
     */
    @ExceptionHandler(BindException.class)
    public ResponseResult<?> processValidException(BindException e) {
        //获取校验错误结果信息，并将信息组装
        List<String> errorStringList = e.getBindingResult().getAllErrors()
                .stream().map(ObjectError::getDefaultMessage).collect(Collectors.toList());
        String errorMessage = String.join("; ", errorStringList);
        log.error(String.format("参数异常:%s", e.getMessage()), e);
        return ResponseResult.systemException(GlobalCodeEnum.GL_FAIL_9998.getCode(),
                errorMessage);
    }

    /**
     * 统一处理参数校验错误异常
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseResult<?> processValidException(IllegalArgumentException e) {
        String errorMessage = String.join("; ", e.getMessage());
        log.error(String.format("参数异常:%s", e.getMessage()), e);
        return ResponseResult.systemException(GlobalCodeEnum.GL_FAIL_9998.getCode(),
                errorMessage);
    }

    /**
     * 统一处理参数校验错误异常
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public ResponseResult<?> processValidException(HttpRequestMethodNotSupportedException e) {
        String[] supportedMethods = e.getSupportedMethods();
        String errorMessage = "此接口不支持" + e.getMethod();
        if (supportedMethods != null) {
            errorMessage += "（仅支持" + String.join(",", supportedMethods) + "）";
        }
        log.error(String.format("请求格式异常:%s", errorMessage), e);
        return ResponseResult.systemException(GlobalCodeEnum.GL_FAIL_9998.getCode(),
                errorMessage);
    }


    /**
     * json序列化失败
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public ResponseResult<?> getPostException(HttpMessageNotReadableException e) {
        log.error(String.format("JSON序列化失败:%s", e.getMessage()), e);
        return ResponseResult.systemError(GlobalCodeEnum.GL_FAIL_10000);
    }
}
